package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
//拦截器是要注册才会生效的
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Map<String, Object> jwt = JwtUtils.parseJwt(token);
        if (ObjectUtils.isEmpty(token) || jwt == null){
            //请求拦截响应401的状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //放回false是请求拦截
            return false;
        }
        //返回true是表示不用拦截请求，请求通过
        return true;
    }
}
